package znbkTestPaperLstjt.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.example.lancooznbk.R;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.EmptyMainLayout;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.List;

import lancooControl.AndroidBug5497Workaround;
import lancooControl.Control;
import lancooControl.PopupWindowMoreFunction;
import znbkChangeCollection.ChangeCollectionEntityModel;
import znbkChangeCollection.ChangeCollectionPresenter.ChangeCollectionPresenter;
import znbkListCtfd.entity.WrongTopicTutoringListEntity;
import znbkListSc.ZnbkPaperScInfor;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperLstjt.ZnbkPaperLstjtInfor;
import znbkTestPaperLstjt.entity.HistoryRecommendQuesPaperEntity;
import znbkTestPaperLstjt.fragmentAdapter.HistoryRecommendQuesPaperFragmentAdapter;
import znbkTestPaperLstjt.presenter.HistoryRecommendQuesPaperPresenter;

/**
 * Created by Administrator on 2018\4\9 0009.
 */

public class HistoryRecommendQuesPaperActivity extends BaseActivity implements View.OnLayoutChangeListener,
        ILoadPaperView<List<HistoryRecommendQuesPaperEntity>> {

    private ScaleButton mSbtnBack;
    private ScaleButton mSbtnAnswerSheet;//答题号菜单
    public static ScaleButton mSbtnSubmit;//提交菜单
    private ScaleButton mSbtnMore;//更多功能菜单
    private ScaleButton mSbtnTimeMeter;//计时器

    public static ViewPager mVp;
    private HistoryRecommendQuesPaperFragmentAdapter mAdapter;

    public static int lastBigViewPage =0;
    public static int currentBigViewPage = 0;

    private HistoryRecommendQuesPaperPresenter mPaperPresenter;
    public static List<HistoryRecommendQuesPaperEntity> mEntityLstjt;

    //Activity最外层的Layout视图
    private View activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    private WrongTopicTutoringListEntity.ParrentQuesListBean mEntity;
    public static final  String PAPER_ENTITY = "paperEntity";
    public static final String PAPER_FROM = "paperFrom";

    public int mQuesOrPaperFrom;

    private LoadingDialog mLoadingDialog;

    private boolean IsSubmitSuccess = false;


    public  static void launch(BaseFragment mContext, WrongTopicTutoringListEntity.ParrentQuesListBean entity, @ZnbkPaperDef.PaperFrom int quesOrPaperFrom){
        ZnbkPaperLstjtInfor.QuesID = entity.getTKQue().getQuesID();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesOrPaperFrom);
        Intent intent = new Intent(mContext.getContext(), HistoryRecommendQuesPaperActivity.class);
        intent.putExtras(bundle);
        mContext.startActivityForResult(intent,1);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.activity_test_paper;
    }

    @Override
    protected void initViews() {
        Log.e("====10101======", "==initViews==");
        AndroidBug5497Workaround.assistActivity(this);
        mPaperPresenter = new HistoryRecommendQuesPaperPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mEntity = (WrongTopicTutoringListEntity.ParrentQuesListBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        currentBigViewPage = 0;

        initView();

        activityRootView = findViewById(R.id.main);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mPaperPresenter.getData(isRefresh);
    }



    /*
    * 初始化界面控件
    * */
    private void initView(){

        mEmptyViewLayout = (EmptyMainLayout) findViewById(R.id.layout_loading);
        /*
        * 返回按钮菜单相关设置
        * */
        mSbtnBack = (ScaleButton) findViewById(R.id.sbtn_back);
        mSbtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityLstjt!=null) {
                   finish();
                }
            }
        });

        /*
        * 答题号按钮菜单相关信息
        * */
        mSbtnAnswerSheet = (ScaleButton) findViewById(R.id.sbtn_answerSheet);
        mSbtnAnswerSheet.setVisibility(View.INVISIBLE);

        /*
        * 提交按钮菜单相关信息
        * */
        mSbtnSubmit = (ScaleButton) findViewById(R.id.sbtn_submit);
        mSbtnSubmit.setVisibility(View.INVISIBLE);

        /*
        * 更多功能按钮菜单相关信息
        * */
        mSbtnMore = (ScaleButton) findViewById(R.id.sbtn_more);
        mSbtnMore.setVisibility(View.INVISIBLE);
        mSbtnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityLstjt!=null) {
                    initPopupWindowMoreFunction();
                }else {
                    Toast.makeText(getApplicationContext(),"数据加载中，请稍后重试...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        /*
        * 计时器显示
        * */
        mSbtnTimeMeter = (ScaleButton) findViewById(R.id.sbtn_timeMeter);
        mSbtnTimeMeter.setVisibility(View.INVISIBLE);

        mVp = (ViewPager) findViewById(R.id.viewpager);



    }

    /*********************
     * ******************
     *实现试卷明细解析
     * *****************
     ******************/
    /************************************************************************************************************************/

    @Override
    public void loadPaperData(List<HistoryRecommendQuesPaperEntity> data) {

        mEntityLstjt =data;

        //这里因为是3.0一下版本，所以需继承FragmentActivity，通过getSupportFragmentManager()获取FragmentManager
        //3.0及其以上版本，只需继承Activity，通过getFragmentManager获取事物
        FragmentManager fm = getSupportFragmentManager();
        //初始化自定义适配器MyFragmentPageAdapter
        mAdapter =  new HistoryRecommendQuesPaperFragmentAdapter(fm);
        MyOnPageChangeListener myOnPageChangeListener = new MyOnPageChangeListener();
        mVp.setOnPageChangeListener(myOnPageChangeListener);
        mVp.setAdapter(mAdapter);

        if(mEntityLstjt!=null){
            mSbtnMore.setVisibility(View.VISIBLE);
        }

    }


    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {
        IsSubmitSuccess = true;
        updateViews(true);
    }

    @Override
    public void openAssessDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {
        mLoadingDialog.dismiss();
//        if (isSucceed){
//            ToastUtils.showShort("提交成功");
//        }else {
//            ToastUtils.showShort("提交失败");
//        }
    }

    @Override
    public void updatingReportResult(boolean isReportSucceed) {
    }

    public  LoadingDialog getLoadingDialog(){
        return mLoadingDialog;
    }

    @Override
    public RxAppCompatActivity getHolderActivity() {
        return null;
    }


    /************************************************************************************************************************/
    /*
    * LazyViewPage切换事件监听
    * */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {

            /*
            * 绑定当前题目小页码
            * */
            lastBigViewPage = currentBigViewPage;

            /*
            * 获取试卷明细相关信息
            * */
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
//            if(mPaperJsonXtfx.getModelPaperInfo().getAnswerState()!=2) {
////                slideSave(lastBigViewPage, false);
//            }
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            currentBigViewPage = arg0;
            Log.e("=======bigViewPage====","===AA==="+currentBigViewPage);

            /*
            * 隐藏软键盘
            * */
            HideKeyboard();

        }

    }


    //隐藏虚拟键盘:Fragment进行切换的时候使用
    public  void HideKeyboard() {
        /**隐藏软键盘**/
        View viewK = this.getWindow().peekDecorView();
        if(viewK != null){
            InputMethodManager inputmanger = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(viewK.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
    * 监听系统home事件
    * */
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        System.out.println("onUserLeaveHint");
    }

    /*
    * 监听系统返回事件
    * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(mEntityLstjt!=null) {
                finish();
            }

            return false;
        }
        return false;
    }




    /******************************************更多功能popupwindow****************************************************/

    private PopupWindowMoreFunction mPopupWindowMoreFunction;
    private void initPopupWindowMoreFunction(){
        if (mPopupWindowMoreFunction == null) {
            //自定义的单击事件
            OnClickLintener paramOnClickListener = new OnClickLintener();
            mPopupWindowMoreFunction = new PopupWindowMoreFunction(this, paramOnClickListener, Control.dip2px(this,140), Control.dip2px(this,80));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            mPopupWindowMoreFunction.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        mPopupWindowMoreFunction.dismiss();
                    }
                }
            });
        }


        //显示当前试题的收藏情况
        if(!mEntityLstjt.get(currentBigViewPage).getTKQue().isIsLike()) {
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
        }else if(mEntityLstjt.get(currentBigViewPage).getTKQue().isIsLike()){
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
        }

        //设置默认获取焦点
        mPopupWindowMoreFunction.setFocusable(true);
        //以某个控件的x和y的偏移量位置开始显示窗口
        mPopupWindowMoreFunction.showAsDropDown(mSbtnMore, Control.dip2px(this,-120), Control.dip2px(this,15));
        //如果窗口存在，则更新
        mPopupWindowMoreFunction.update();
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_dictionary:
                    System.out.println("=======电子词典=========");
                    mPopupWindowMoreFunction.dismiss();
                    startActivity(new Intent(getApplicationContext(), DictionaryActicity.class));
                    break;
                case R.id.layout_difficult_question:
                    System.out.println("=======收藏与否=========");
                    int CollectionFlag = -1;
                    if(!mEntityLstjt.get(currentBigViewPage).getTKQue().isIsLike()) {
                        CollectionFlag = 1;
                        mEntityLstjt.get(currentBigViewPage).getTKQue().setIsLike(true);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
                    }else if(mEntityLstjt.get(currentBigViewPage).getTKQue().isIsLike()){
                        CollectionFlag = 0;
                        mEntityLstjt.get(currentBigViewPage).getTKQue().setIsLike(false);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
                    }
                    String QuesID = mEntityLstjt.get(currentBigViewPage).getTKQue().getQuesID();

                    String Theme = "";
                    if(!mEntityLstjt.get(currentBigViewPage).getTKQue().getQuesBrief().equals("")){
                        Theme = mEntityLstjt.get(currentBigViewPage).getTKQue().getQuesBrief();
                    }else{
                        if(!mEntityLstjt.get(currentBigViewPage).getTKQue().
                                getChildList().get(0).getChildAsk().equals("")){
                            Theme = mEntityLstjt.get(currentBigViewPage).getTKQue().
                                    getChildList().get(0).getChildAsk();
                        }else{
                            Theme = mEntityLstjt.get(currentBigViewPage).getTKQue().
                                    getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                        }
                    }
                    String GenreID = mEntityLstjt.get(currentBigViewPage).getTKQue().getGenreID();
                    String TypeNo = mEntityLstjt.get(currentBigViewPage).getTKQue().getTypeNo();
                    String ResType = mEntityLstjt.get(currentBigViewPage).getTKQue().getResType();
                    if(ResType.equals("Q")){
                        ResType =  TypeNo;
                    }

                    ZnbkPaperScInfor.changeCollectionEntityModel =  new ChangeCollectionEntityModel(CollectionFlag,
                            GenreID,QuesID,ResType, UserInfo.StageNo, UserInfo.StuId,UserInfo.SubjectId,Theme,TypeNo);

                    changeCollection();
                    break;

                default:
                    break;
            }

        }

    }
    /*
    * 加入收藏、取消收藏
    * */
    ChangeCollectionPresenter mChangeCollectionPresenter;
    private void changeCollection(){
        mChangeCollectionPresenter = new ChangeCollectionPresenter(this,mQuesOrPaperFrom);
        mChangeCollectionPresenter.getData(false);
    }
    /********************************************************************************************************************/




    @Override
    protected void onResume() {
        super.onResume();
        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        if (bottom > oldBottom){
            //输入法软键盘关闭
            Log.d(">>>>>>>>>crg", "输入法软键盘关闭: ");
        } else if (bottom < oldBottom){
            //输入法软键盘打开
            Log.d(">>>>>>>>>crg", "输入法软键盘打开: ");
        }

    }

}